<script setup lang="ts">
import to from 'await-to-js'
import { getCodeImg } from '@/api/login'
import type { FormInstance } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/public/user'
const router = useRouter()
const useStore = useUserStore()
const codeImg = ref('')
const isLoading = ref(false)
const isLoginForm = ref(true)
const formRef = ref<FormInstance>()

const data = reactive({
  form: {
    roleIds: [],
  },
  rules: {
    username: [{ required: true, message: '请输入用户名' }],
    password: [{ required: true, message: '请输入密码' }],
    confirmPassword: [
      { required: true, message: '请输入密码' },
      {
        pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*()_+~`|}{[\]:;'<>,./?])(?=.*[^\s]).{8,16}$/,
        message: '密码中必须包含字母、数字、特殊字符，长度8-16',
      },
    ],
    code: [{ required: true, message: '请输入验证码' }],
  },
})
const { form, rules } = toRefs<any>(data)

const login = async () => {
  const pageType = isLoginForm.value ? 'Login' : 'Register'
  const isValidate = await to(formRef.value.validate())
  if (isValidate[0]) return
  if (pageType === 'Register' && form.value.password !== form.value.confirmPassword) {
    ElMessage.error('两次密码输入不一致')
    return
  }
  isLoading.value = true
  const [err] = await to(isLoginForm.value ? useStore.login(form.value) : useStore.register(form.value))
  isLoading.value = false
  if (err) {
    ElMessage.error(err)
    getCodeImage()
    return
  }
  isLoading.value = true
  const [err2] = await to(useStore.getInfo())
  isLoading.value = false
  if (err2) return
  router.push({ path: '/' })
}

const keyDown = (e: KeyboardEvent) => {
  // 回车则执行登录方法 enter键的ASCII是13
  if (e.keyCode === 13) {
    login()
  }
}
const getCodeImage = async () => {
  const [err, res] = await to(getCodeImg())
  if (err) return
  console.log(res)
  codeImg.value = URL.createObjectURL(res) || ''
}

const switchStatus = () => {
  form.value = {}
  formRef.value.clearValidate()
  formRef.value.resetFields()
  isLoginForm.value = !isLoginForm.value
}
onBeforeMount(() => {
  useStore.isLogin && router.push('/')
  getCodeImage()
})
onMounted(() => {
  window.addEventListener('keydown', keyDown)
})
onUnmounted(() => {
  window.removeEventListener('keydown', keyDown, false)
})
</script>

<template>
  <div class="login-container">
    <div class="content">
      <img src="@/assets/image/login/logo.png" width="384" height="340" alt="" />
      <div class="login-content">
        <div class="title">{{ isLoginForm ? '用户登录' : '用户注册' }}</div>
        <el-form ref="formRef" :model="form" :rules="rules" class="login-form" label-width="80px">
          <el-form-item label-width="0" prop="username">
            <el-input v-model="form.username" placeholder="用户名">
              <template #prefix>
                <div class="flex items-center h-full pl-1 pr-1">
                  <img src="@/assets/image/login/user-icon.png" width="22" height="22" alt="" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="password">
            <el-input v-model="form.password" placeholder="密码" show-password>
              <template #prefix>
                <div class="flex items-center h-full pl-1 pr-1">
                  <img src="@/assets/image/login/password.png" width="22" height="22" alt="" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="confirmPassword" v-if="!isLoginForm">
            <el-input v-model="form.confirmPassword" placeholder="确认密码" show-password>
              <template #prefix>
                <div class="flex items-center h-full pl-1 pr-1">
                  <img src="@/assets/image/login/password.png" width="22" height="22" alt="" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label-width="0" prop="code" style="margin-bottom: 14px">
            <el-input v-model="form.code" placeholder="验证码">
              <template #prefix>
                <div class="flex items-center h-full pl-1 pr-1">
                  <img src="@/assets/image/login/code-icon.png" width="22" height="22" alt="" />
                </div>
              </template>
              <template #suffix>
                <div class="flex items-center h-full pr-2">
                  <img :src="codeImg" width="90" alt="" class="cursor-pointer" @click="getCodeImg" />
                </div>
              </template>
            </el-input>
          </el-form-item>
          <div class="login-tip">
            <span>{{ isLoginForm ? '没有账号？' : '已有账号？' }}</span>
            <span @click="switchStatus()">{{ isLoginForm ? '立即注册' : '登录' }}</span>
          </div>
        </el-form>
        <el-button type="primary" class="login-btn" @click="login" :loading="isLoading">{{ isLoginForm ? '登录' : '注册' }} </el-button>
      </div>
    </div>
    <div class="Copyright">Copyright 1999-2023中国移动版权所有 | 京iCP备05002571号</div>
  </div>
</template>

<style scoped lang="scss">
.login-container {
  width: 100%;
  height: 100vh;
  margin-top: -60px;
  padding-top: 60px;
  background-image: url('@/assets/image/login/backgroud.png');
  background-size: cover;
  background-repeat: no-repeat;
  font-family: MiSans-Medium, MiSans;
}
.Copyright {
  position: absolute;
  width: 100%;
  bottom: 26px;
  text-align: center;
  font-size: 14px;
  font-family: MiSans-Regular, MiSans;
  font-weight: 400;
  color: #747882;
  line-height: 19px;
}
.content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .login-content {
    margin-left: 138px;
    width: 420px;
    //height: 413px;
    background: #ffffff;
    box-shadow: 0px 2px 16px 0px rgba(0, 0, 0, 0.12);
    border-radius: 4px;
    opacity: 1;
    padding: 40px;
    .title {
      font-size: 24px;
      font-weight: 600;
      color: #1d263d;
      line-height: 32px;
      text-align: center;
    }
    .login-form {
      margin-top: 28px;
      margin-bottom: 36px;
      :deep() {
        .el-input__inner {
          height: 44px;
          line-height: 44px;
        }
      }
    }
    .login-btn {
      width: 100%;
      font-size: 16px;
      padding: 20px 0;
    }
    .login-tip {
      span {
        font-size: 12px;
      }
      span:first-child {
        color: #000000;
      }
      span:last-child {
        color: #3e8efd;
        cursor: pointer;
      }
    }
  }
}
</style>
